package TCP04;

import java.io.*;
import java.net.Socket;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
class ServiceReaderThread implements Runnable {
    private Socket socket;

    public ServiceReaderThread() {
    }

    public ServiceReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //3.从Socket管道中得到一个字节输入流
            InputStream inputStream = socket.getInputStream();
            //4.把字节输入流包装成字符输入流来接收文本消息
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            //5.读取消息
            String msg;
            //循环接收到消息，如果没有消息后会报错
            while ((msg = br.readLine()) != null) {
                System.out.println(socket.getRemoteSocketAddress() + "发来了：" + msg);
                //把这个消息进行端口转发给全部客户端
                sendMsgToAll(msg);
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress() + "下线了");
            ServiceDemo2.list.remove(socket);
        }
    }
    private void sendMsgToAll(String msg) throws Exception{
        for (Socket socket : ServiceDemo2.list) {
            PrintStream ps = new PrintStream(socket.getOutputStream());
            ps.println(msg);
            ps.flush();
        }
    }
}
